package com.dianjing.dianqun.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dianjing.dianqun.common.ResponseData;
import com.dianjing.dianqun.common.base.BaseRestController;
import com.dianjing.dianqun.model.FriendsRelation;
import com.dianjing.dianqun.model.Site;
import com.dianjing.dianqun.model.User;
import com.dianjing.dianqun.model.UserExt;
import com.dianjing.dianqun.model.dto.UserDTO;
import com.dianjing.dianqun.model.dto.UserFlowDTO;
import com.dianjing.dianqun.service.FriendsRelationService;
import com.dianjing.dianqun.service.SiteService;
import com.dianjing.dianqun.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * @date : 2017年10月13日
 * 
 * @author: baoyongtao
 * 
 * @see :
 * 
 */

@Api(value = "UserApiController", description = "用户相关api")
@RestController
@RequestMapping("/api/user")
public class UserApiController extends BaseRestController {

	@Autowired
	private UserService userService;

	@Autowired
	private FriendsRelationService friendsRelationService;
	
	@Autowired
	private SiteService siteService;
	

	@ApiOperation(value = "查询用户是否为点拍用户，检查是否已经初始化站点", notes = "根据用户id查询用户是否为点拍用户，检查是否已经初始化站点")
	@GetMapping("/authorization")
	@ApiImplicitParam(name = "userId", value = "用戶id", dataType = "int", required = true, paramType = "query")
	public ResponseData authorization(@RequestParam(required = true) Integer userId) {
		User user = userService.selectByPrimaryKey(userId);
		if(null==user) {
			return new ResponseData(ResponseData.STATUS_ERROR, "用户不存在", null);
		}
		Site site = siteService.selectSitelByUserId(userId);
		if(null==site) {
			return new ResponseData(ResponseData.STATUS_ERROR, "没有找到用户的站点", false);
		}
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", site.getIsInitChnnel());
	}

	

	@ApiOperation(value = "关于我们的信息获取", notes = "关于我们的信息获取")
	@GetMapping("/search/about")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "siteId", value = "站点id", dataType = "int", required = true, paramType = "query"),
		@ApiImplicitParam(name = "userId", value = "当前用户id", dataType = "int", required = false, paramType = "query")
	})
	@ApiResponses({
		@ApiResponse(code=0, message = "未关注（显示 关注 ）"),
		@ApiResponse(code=1, message = "已关注（显示 已关注 ）"),
		@ApiResponse(code=2, message = "已互相关注（显示 已互关）"),
	})
	public ResponseData searchAbout(@RequestParam(value = "siteId" ,required = true) Integer siteId,@RequestParam(value = "userId" ,required =false )Integer userId) {
		Map<Object,Object> map = Maps.newHashMap();
		User follow = userService.selectUserBySiteId(siteId);
		if (follow == null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "操作失败，用户可能不存在", null);
		}
		map.put("info",follow);
		if(userId!=null) {
			FriendsRelation f1 = friendsRelationService.selectMyFlowUser(userId, follow.getUserId());
			FriendsRelation f2 = friendsRelationService.selectMyFlowUser(follow.getUserId(),userId);
			Integer flowStatus= (f1!=null && f2!=null)?2:(f1==null?0:1);		
			map.put("flowStatus", flowStatus);
		}else {
			map.put("flowStatus", 1);
		}
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", map);
	}
	
	
	
	@ApiOperation(value = "查询用户", notes = "根据点睛号/手机号查询用户")
	@GetMapping("/search")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "当前用户信息", dataType = "int", required = true, paramType = "query"),
		@ApiImplicitParam(name = "keyword", value = "点睛号/手机号/用户名", dataType = "string", required = true, paramType = "query")
	})
	@ApiResponses({
		@ApiResponse(code=0, message = "未关注（显示 关注 ）"),
		@ApiResponse(code=1, message = "已关注（显示 已关注 ）"),
		@ApiResponse(code=2, message = "已互相关注（显示 已互关）"),
	})
	public ResponseData get(@RequestParam(required = true) String keyword,@RequestParam(value = "userId" ,required =true )Integer userId) {
		UserDTO follow = userService.searchUserByKeyword(keyword);
		User u = userService.selectByPrimaryKey(userId);
		if (u == null || follow == null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "操作失败，用户可能不存在", null);
		}
		FriendsRelation f1 = friendsRelationService.selectMyFlowUser(userId, follow.getUserId());
		FriendsRelation f2 = friendsRelationService.selectMyFlowUser(follow.getUserId(),userId);
		Integer flowStatus= (f1!=null && f2!=null)?2:(f1==null?0:1);		
		follow.setFlowStatus(flowStatus);
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", follow);
	}

	@ApiOperation(value = "查询用户基本信息", notes = "根据用户id查询用户基本信息")
	@GetMapping("/info/{id}")
	@ApiImplicitParam(name = "id", value = "用戶id", dataType = "int", required = true, paramType = "path")
	public ResponseData getInfo(@PathVariable(required = true) Integer id) {
		UserExt ext = userService.selectUserExtInfo(id);
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", ext);
	}

	@ApiOperation(value = "查询好友关系/我的关注", notes = "根据用户id查询所有的好友和关系")
	@GetMapping("/friend/{id}")
	@ApiImplicitParam(name = "id", value = "用戶id", dataType = "int", required = true, paramType = "path")
	public ResponseData userFriend(@PathVariable(required = true) Integer id) {
		List<UserDTO> list = userService.selectFriendUser(id);
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", list);
	}

	@ApiOperation(value = "查询好友关系/关注我的", notes = "根据用户id查询所有的好友和关系")
	@GetMapping("/friend/follow/{id}")
	@ApiImplicitParam(name = "id", value = "用戶id", dataType = "int", required = true, paramType = "path")
	public ResponseData myFollowFriend(@PathVariable(required = true) Integer id) {
		List<UserDTO> list = userService.selectFollowMeUser(id);
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", list);
	}

	@ApiOperation(value = "用户关注", notes = "根据用户id和关注者id绑定关系")
	@GetMapping("/follow/{userId}/{followId}")
	@ApiResponses({
		@ApiResponse(code=0, message = "未关注（显示 关注 ）"),
		@ApiResponse(code=1, message = "已关注（显示 已关注 ）"),
		@ApiResponse(code=2, message = "已互相关注（显示 已互关）"),
	})
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用戶id", dataType = "int", required = true, paramType = "path"),
			@ApiImplicitParam(name = "followId", value = "被关注用戶id", dataType = "int", required = true, paramType = "path"),
			@ApiImplicitParam(name = "status", value = "关注状态（0：关注  1：取消关注）", dataType = "int", required = true, paramType = "query") })
	public ResponseData follow(@PathVariable(required = true) Integer userId,
			@PathVariable(required = true) Integer followId,
			@RequestParam(required = false, defaultValue = "0") Integer status) {
		User followUser = userService.selectByPrimaryKey(followId);
		User user = userService.selectByPrimaryKey(userId);
		if (followUser == null || user == null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "操作失败，用户可能不存在", null);
		}
		Integer success=null;
		if (status.equals(0)) {// 关注
			userService.followUser(userId, followId);
			//查询 粉丝是否关注我 根据 是否关注 在确定我的关注状态  为null 用户未关注我 ， 显示 已关注。  不为null ， 用户关注了我 显示已关注
			success = friendsRelationService.selectMyFlowUser(followId, userId)==null?1:2;
		} else if (status.equals(1)) {// 取消关注
			userService.cancelFollowUser(userId, followId);
			success = 0;//取消
		}
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", success);

	}

	
	@ApiOperation(value = "根据站点id实现用户关注", notes = "根据站点id实现用户的关注")
	@GetMapping("/follow/bysite")
	@ApiResponses({
		@ApiResponse(code=0, message = "未关注（显示 关注 ）"),
		@ApiResponse(code=1, message = "已关注（显示 已关注 ）"),
		@ApiResponse(code=2, message = "已互相关注（显示 已互关）"),
	})
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用戶id", dataType = "int", required = true, paramType = "query"),
			@ApiImplicitParam(name = "followSiteId", value = "被关注用戶站点id", dataType = "int", required = true, paramType = "query"),
			@ApiImplicitParam(name = "status", value = "关注状态（0：关注  1：取消关注）", dataType = "int", required = true, paramType = "query") })
	public ResponseData followBySiteId(@RequestParam(required = true) Integer userId,
			@RequestParam(required = true) Integer followSiteId,
			@RequestParam(required = false, defaultValue = "0") Integer status) {
		User followUser = userService.selectUserBySiteId(followSiteId);
		User user = userService.selectByPrimaryKey(userId);
		if (followUser == null || user == null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "操作失败，用户可能不存在", null);
		}
		Integer followId=followUser.getUserId();
		Integer success=null;
		if (status.equals(0)) {// 关注
			userService.followUser(userId,followId);
			//查询 粉丝是否关注我 根据 是否关注 在确定我的关注状态  为null 用户未关注我 ， 显示 已关注。  不为null ， 用户关注了我 显示已关注
			success = friendsRelationService.selectMyFlowUser(followId, userId)==null?1:2;
		} else if (status.equals(1)) {// 取消关注
			userService.cancelFollowUser(userId, followId);
			success = 0;//取消
		}
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", success);

	}
	
	
	@ApiOperation(value = "查询我关注的/关注我的的用户列表", notes = "根据用户id查询所有的好友和关系 0：待关注 1 已关注 2 互相关注")
	@GetMapping("/friend/list/{id}")
	@ApiImplicitParam(name = "id", value = "用戶id", dataType = "int", required = true, paramType = "path")
	public ResponseData list(@PathVariable(required = true) Integer id) {
		// 查询我关注的我的粉丝 (先查詢我的粉絲 在查我是否關注了我的粉絲)
		//要去除 互相关注的人 集合  单独封装
		List<UserDTO> unFlowUserList= new ArrayList<UserDTO>();
		List<Integer> hzgzList= new ArrayList<Integer>();
		for (UserDTO userDTO :  userService.selectUserByHXGZ(id)) {
			hzgzList.add(userDTO.getUserId());
		}
		List<UserDTO> myFansList = userService.selectFollowMeUser(id);// 我的粉丝
		List<UserDTO> list = new ArrayList<UserDTO>();
		for (UserDTO user : myFansList) {
			if(hzgzList.contains(user.getUserId())) {
				unFlowUserList.add(user);
				user.setFlowStatus(0);
			}else {
				list.add(user);
			}
		}
		List<UserDTO> flowMeList = userService.selectFriendUser(id);// 我关注的
		for (UserDTO user : flowMeList) {
			if(hzgzList.contains(user.getUserId())) {
				continue;
			}
			user.setFlowStatus(1);
			list.add(user);
		}
		//处理互相关注的状态
		for (UserDTO userDTO : unFlowUserList) {
			userDTO.setFlowStatus(2);
		}
		list.addAll(unFlowUserList);
		return new ResponseData(ResponseData.STATUS_OK, "请求成功", list);
	}

	@ApiOperation(value = "查询用户的最近访客", notes = "根据用户的id查询用户的最近访客")
	@GetMapping(value = "/latelyUser/{userId}")
	@ApiImplicitParams({ @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页多少记录", paramType = "query"),
			@ApiImplicitParam(dataType = "int", name = "pageNum", value = "当前页", paramType = "query"),
			@ApiImplicitParam(dataType = "int", name = "userId", required = true, value = "用户id", paramType = "path") })
	public ResponseData query(@RequestParam(defaultValue = "10") Integer pageSize,
			@PathVariable(required = true) Integer userId, @RequestParam(defaultValue = "1") Integer pageNum) {
		Site site = siteService.selectSitelByUserId(userId);
		if(null!=site) {
			PageHelper.startPage(pageNum, pageSize);
			PageInfo<UserFlowDTO> page = new PageInfo<UserFlowDTO>(userService.selectLatelyUserList(site.getSiteId(),userId,null));
			for (UserFlowDTO user : page.getList()) {
				FriendsRelation selectMyFlowUser = friendsRelationService.selectMyFlowUser(userId,user.getUserId());
				if(selectMyFlowUser!=null) {
					user.setIsBothFriends(selectMyFlowUser.getBothFriends());
				}else {
					user.setIsBothFriends(false);
				}
			}
			return new ResponseData(ResponseData.STATUS_OK, "查询完成", page);
		}
		return new ResponseData(ResponseData.STATUS_ERROR, "查询失败，参数可能不对", new String[]{});
	}
	@Value("${system.want.site.phone}") 
	private String phone;
	@Value("${system.want.site.kefu.phone}")
	private String kefu;
	@Value("${system.want.site.email}")
	private String email;
	@Value("${system.want.site.qrocde.path}")
	private String qrocde;
	@Value("${system.domain}")
	private String domain;
	
	
	@ApiOperation(value = "获取客服信息", notes = "获取客服信息")
	@GetMapping("/wantSiteInfo")
	public ResponseData wantSiteInfo() {
		Map<Object,Object> map = Maps.newHashMap();
		map.put("phone", phone);
		map.put("kefuPhone", kefu);
		map.put("email", email);
		map.put("qrocde", domain+qrocde);
		return new ResponseData(ResponseData.STATUS_OK, "完成",map);
	}
	
	
	@ApiOperation(value = "用户登录信息id转换", notes = "用户登录信息id转换")
	@ApiImplicitParam(required = true , paramType = "query" , name = "userId")
	@GetMapping("/convertUserInfo")
	public ResponseData convertUserInfo(@RequestParam(required = true , name = "userId")Integer userId) {
		UserDTO  user  = userService.convertUser(userId);
		return new ResponseData(ResponseData.STATUS_OK, "完成",user);
	}
	
}
